import { h, onMounted, reactive, ref, toRaw } from "vue";
import type { PaginationProps } from "@pureadmin/table";
import type { FormItemProps } from "../utils/types";
import { addDialog } from "@/components/ReDialog";
import { deviceDetection } from "@pureadmin/utils";
import editForm from "../form.vue";
import { message } from "@/utils/message";
import {
  getDepartmentListApi,
  createDepartmentApi,
  updateDepartmentApi,
  delDepartmentApi,
  getDepartmentShowApi,
  getDeptListApi,
  // jobTitleStoreApi
} from "@/api/user";

export function useCorps() {
  const form = reactive({
    page: 1,
    perPage: 20,
    departmentId: "",
    name: "",

  });
  const formRef = ref();
  const dataList = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const higherDeptOptions = ref();
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "部门名称",
      prop: "name",
    },
	{
	  label: "上级部门",
	  prop: "parent",
	  formatter:(row: any)=> {
	  	return row.parent?.name
	  },
	},
    {
      label: "排序",
      prop: "sort"
    },
	{
	  label: "创建时间",
	  prop: "createdAt"
	},
    {
      label: "操作",
      fixed: "right",
      slot: "operation",
	  width: 120
    }
  ];
  function handleSizeChange(val: number) {
    loading.value = true;
    form.page = 1;
    form.perPage = val;
    getDepartmentListApi(toRaw(form)).then(result => {
      dataList.value = result.result.list;
      pagination.total = result.result.total;
      pagination.pageSize = result.result.perPage*1;
      pagination.currentPage = 1;
    });
    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  function handleCurrentChange(val: number) {
    loading.value = true;
    form.page = val;
    getDepartmentListApi(toRaw(form)).then(result => {
      dataList.value = result.result.list;
      pagination.total = result.result.total;
      pagination.pageSize = result.result.perPage*1;
      pagination.currentPage = result.result.page*1;
    });
    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  async function onSearch() {
    loading.value = true;
    const { result } = await getDepartmentListApi(toRaw(form));
    dataList.value = result.list;
    pagination.total = result.total;
    pagination.pageSize = result.perPage*1;
    pagination.currentPage = result.page*1;

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };
  function formatHigherDeptOptions(treeList: any) {
      // 根据返回数据的status字段值判断追加是否禁用disabled字段，返回处理后的树结构，用于上级部门级联选择器的展示（实际开发中也是如此，不可能前端需要的每个字段后端都会返回，这时需要前端自行根据后端返回的某些字段做逻辑处理）
      if (!treeList || !treeList.length) return;
      const newTreeList = [];
      for (let i = 0; i < treeList.length; i++) {
        treeList[i].disabled = treeList[i].status === 0 ? true : false;
        formatHigherDeptOptions(treeList[i].children);
        newTreeList.push(treeList[i]);
      }
      return newTreeList;
    }
  const formInline = ref();
  async function openDialog(title = "创建部门", row?: FormItemProps) {
	  // 归属部门
	  const deptList = await getDeptListApi();
    if (`${title}` == "创建部门") {
      formInline.value = {
        title: "创建部门",
		higherDeptOptions: deptList.result,
		sort: 1,
		parentId: 0,
      };
    } else {
      const { result } = await getDepartmentShowApi({ departmentId: row.departmentId });
      formInline.value = {
        title: "编辑部门",
		higherDeptOptions: deptList.result,
        departmentId: result?.id ?? "",
        name: result?.name ?? "",
        sort: result?.sort ?? 0,
        parentId: result?.parentId ?? 0
      };

    }
    addDialog({
      title: `${title}`,
      props: {
        formInline: formInline
      },
      width: "44%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;

		const params = {
			departmentId: curData.departmentId,
			name: curData.name,
			sort: curData.sort,
			parentId: curData.parentId
		}
        function chores() {
          message(`${title}成功`, {
            type: "success"
          });
          done();
          onSearch();
        }

        FormRef.validate(valid => {
          if (valid) {
            if (title === "创建部门") {
              createDepartmentApi(params)
                .then(() => {
                  chores();
                })
                .catch(error => {
                  message(error.response.data.msg ?? "操作失败,请联系管理员", {
                    type: "error"
                  });
                });
            } else {
              updateDepartmentApi(params)
                .then(() => {
                  chores();
                })
                .catch(error => {
                  message(error.response.data.msg ?? "操作失败,请联系管理员", {
                    type: "error"
                  });
                });
            }
          }
        });
      }
    });
  }
  onMounted(async () => {
    onSearch();

  });

  function handleDelete(row) {
    delDepartmentApi({ departmentId: row.departmentId }).then(() => {
      message(`删除成功`, { type: "success" });
      onSearch();
    });
  }
  function confirmStatus() {
    alert("审核通过");
  }
  function refusedStatus() {
    alert("审核拒绝");
  }
  return {
    form,
    isShow,
    loading,
    columns,
    dataList,
    pagination,
    onSearch,
    resetForm,
    openDialog,
    handleSizeChange,
    handleCurrentChange,
    deviceDetection,
    handleDelete,
    confirmStatus,
    refusedStatus
  };
}
